package com.megagoodsoftware.smugmug;

import java.io.*;

import org.apache.http.entity.*;

public class CountingHttpEntity extends AbstractHttpEntity {

	private final AbstractHttpEntity entity;
	private final ProgressListener listener;

	public CountingHttpEntity(final AbstractHttpEntity entity,
			final ProgressListener listener) {
		super();
		this.entity = entity;
		this.listener = listener;
	}

	@Override
	public InputStream getContent() throws IOException, IllegalStateException {
		return entity.getContent();
	}

	@Override
	public long getContentLength() {
		return entity.getContentLength();
	}

	@Override
	public boolean isRepeatable() {
		return entity.isRepeatable();
	}

	@Override
	public boolean isStreaming() {
		return entity.isStreaming();
	}

	@Override
	public void writeTo(OutputStream out) throws IOException {
		entity.writeTo(new CountingOutputStream(out, listener));
	}

	public static interface ProgressListener {

		void transferred(int num);

	}

	public static class CountingOutputStream extends FilterOutputStream {
		private final ProgressListener listener;
		private int written;

		public CountingOutputStream(final OutputStream out,
				final ProgressListener listener) {
			super(out);
			this.listener = listener;
			this.written = 0;
		}

		@Override
		public void write(byte[] b, int off, int len) throws IOException {
			// this will eventually call write(int b) 
			super.write(b, off, len);
			// seems like android upload is only calling this one.
			listener.transferred(written);
		}

		@Override
		public void write(int b) throws IOException {
			super.write(b);
			written++;
		}

		@Override
		public void write(byte[] buffer) throws IOException {
			// TODO Auto-generated method stub
			super.write(buffer);
		}

	}
}
